package cn.maihe.elg.operation.utils;

import cn.hutool.crypto.digest.MD5;
import cn.maihe.elg.operation.model.bo.OfdStructXmlBO;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * @Description
 * @Author WJH
 * @Date 2021/09/27
 */
@Slf4j
public class OfdStructXmlUtil {

    public static String genOfdXmlFile(String acceptOrderNo) {

        return null;
    }


    public static String genOfdXmlFile() throws Exception {

        StringBuilder info = new StringBuilder();
        info.append("<ORDER_ID>42e1e31d59da452a90397e2529660a18</ORDER_ID>");
        info.append("<GUARANTEE_NO>DXDB1919998957900034049</GUARANTEE_NO>");
        info.append("<TENDER_INFO APPROVAL_CODE=\"\" INVEST_PROJECT_CODE=\"\" TENDER_PROJECT_CODE=\"E3502030201100103001\" TENDER_PROJECT_NAME=\"测试-市政工程-施工（2024年8月修订版）-综合评估法B类-20240915ZGX\" SECTION_CODE=\"E3502030201100103001001\" SECTION_NAME=\"测试-市政工程-施工（2024年8月修订版）-综合评估法B类-20240915ZGX\" CONTRACT_RECKON_PRICE=\"15215645.00\" TENDERER=\"福建丰达建设发展有限公司\" TENDERER_CREDIT_CODE=\"913506277242282547\" TENDERER_BANK_CODE=\"\" TENDERER_BANK_OPENBANK=\"\" TENDERER_BANK_ACCOUNT=\"福建丰达建设发展有限公司\" TENDERER_CONTACT=\"刘平\" TENDERER_CONTACT_TEL=\"15060008009\" CITY_CODE=\"350203\" TENDER_PROJECT_TYPE=\"A02\" BID_OPEN_TIME=\"20270915105658\" VALID_PERIOD=\"320\" BID_BOND=\"550000.00\" TENDER_NOTICE_URL=\"A02\" TENDER_FILE_URL=\"http://test-file-server.okap.com/file/download/051438b9ebf14f17b559052e7384bffa\" TENDER_FILE_MD5=\"B31928E3AC52E48CD2907CAE8CC19AE6\"></TENDER_INFO>");
        info.append("<GUARANTOR GUARANTOR_NAME=\"泉州丰泽得兴融资担保有限公司\" GUARANTOR_CREDIT_CODE=\"91350503MA35A8601G\" GUARANTOR_LEGAL_PERSON=\"王茜\" GUARANTOR_LEGAL_IDCARD_TYPE=\"01\" GUARANTOR_LEGAL_IDCARD=\"210603198809020020\" BANK_CODE=\"\" GUARANTOR_ADDRESS=\"福建省福州市台江区广达路68号金源大广场东区15层F单元\" GUARANTOR_EMAIL=\"860682131qq.com\" GUARANTOR_POSTCODE=\"350001\" GUARANTOR_PHONE=\"13559331555\" GUARANTOR_TAX=\"\" GUARANTOR_BUSSINESS_NAME=\"林文渊\" GUARANTOR_BUSSINESS_TEL=\"13559331555\" GUARANTOR_TECHNOLOGY_NAME=\"林文渊\" GUARANTOR_TECHNOLOGY_TEL=\"13559331555\"></GUARANTOR>");
        info.append("<BIDDER BIDDER_NAME=\"福建丰达建设发展有限公司\" BIDDER_CREDIT_CODE=\"913506277242282547\" BIDDER_CONTACT_NAME=\"刘平\" BIDDER_CONTACT_TEL=\"15060008009\" BIDDER_CONTACT_IDCARD=\"350104198803134449\" BIDDER_CONTACT_IDCARD_TYPE=\"01\" BIDDER_ADDRESS=\"福建省漳州市南靖县山城镇人民广场1号\" BIDDER_EAMIL=\"454152231@qq.com\" LEGAL_PERSON_NAME=\"黄景禧\" LEGAL_PERSON_IDCARD=\"350625198412120014\" LEGAL_PERSON_IDCARD_TYPE=\"01\" LEGAL_PERSON_TEL=\"13615005316\"></BIDDER>");
        info.append("<GUARANTEE_INFO GUARANTEE_NO=\"DXDB1919998957900034049\" CREATE_TIME=\"20250507145338\" SERVICE_BEGIN_TIME=\"20270915105658\" SERVICE_END_TIME=\"20280828105658\" BID_BOND=\"550000.00\" AMOUNT=\"660.00\" RATE=\"0.15\" PAY_TYPE=\"4\" PAY_ACCOUNT=\"0000018237002012\" PAY_NAME=\"福建丰达建设发展有限公司\" PAY_PHONE=\"15060008009\" PAY_BANK_OPENBANK=\"泉州银行股份有限公司漳州龙文支行\" GUARANTEE_DUTY=\"连带责任保证\" GUARANTEE_PROPERTY=\"独立保函\" CLAIM_CLAUSE=\"1、投标人在投标有效期内撤销或修改其投标文件的；2、投标人中标后，非因不可抗力原因放弃中标、无正当理由不与招标人订立合同、在签订合同时向招标人提出附加条件、或者不按照招标文件要求提交履约担保金的；3、投标人的投标文件存在投标须知第 20.6 款规定的雷同情形之一；4、投标人中标后，因违法行为导致中标被依法确认无效的；5、法律、法规规定的其他没收投标保证金情形。本保函在投标有效期到期后 28 日（含）内或招标人延长投标有效期后的到期日后 28日（含）内保持有效，延长投标有效期无须通知我方，但任何索款要求应在投标有效期内送达我方。保函失效后请将本保函交投标人退回我方注销。本保函项下所有权利和义务均受中华人民共和国法律管辖和制约。\" PAY_LIMITATION=\"7\" BANK_RECORD_NO=\"无\" APPLICABLE_LAW=\"适用法律：担保法、保险法、《独立保函司法解释》（法释〔2016〕24 号）\" REMARK=\"\"></GUARANTEE_INFO>");
        info.append("<BENEFICIARY_INFO BENEFICIARY=\"福建丰达建设发展有限公司\" BENEFICIARY_CREDIT_CODE=\"913506277242282547\" BENEFICIARY_BANK_ACCOUNT=\"福建丰达建设发展有限公司\" BENEFICIARY_BANK_CODE=\"\" BENEFICIARY_BANK_OPENBANK=\"\" BENEFICIARY_CONTACT=\"刘平\" BENEFICIARY_CONTACT_TEL=\"15060008009\"></BENEFICIARY_INFO>");
        info.append("<GUARANTEE_ATTACHMENT WARRANTY_FILE_NAME=\"电子保单（合同）原文件.pdf\" WARRANTY_MD5=\"59C3E0739AB7A6024276CC914C32CB8F\" WARRANTY_PDF_FILE_NAME=\"电子保单（合同）PDF文件.pdf\" WARRANTY_PDF_MD5=\"59C3E0739AB7A6024276CC914C32CB8F\" ORDER_FILE_NAME=\"电子保函申请单原文件.pdf\" ORDER_MD5=\"9774560E57EEED4A7F83D3A9BA7943C2\" ORDER_PDF_FILE_NAME=\"电子保函申请单PDF文件.pdf\" ORDER_PDF_MD5=\"9774560E57EEED4A7F83D3A9BA7943C2\" QUALFICATION_FILE_NAME=\"企业资质文件.jpg\" QUALFICATION_FILE_MD5=\"66CC5FBC1551C0E0B808B856C766E7B9\" BUSINESS_LICENSE_FILE_NAME=\"企业营业执照.jpg\" BUSINESS_LICENSE_MD5=\"0609A485C414281F6FBC3D970B0CF05E\" OTHER_FIE_NAME=\"到账证明.pdf\" OTHER_FIE_MD5=\"8EFB66D5C30AC1853BEA9F1290CC3D86\"></GUARANTEE_ATTACHMENT>");
        info.append("<INVOICE_INFO INVOICE_TITLE=\"福建丰达建设发展有限公司\" INVOICE_NO=\"20882505071431111504\" CUSTOMER_NAME=\"福建丰达建设发展有限公司\" CUSTOMER_CREDIT_CODE=\"913506277242282547\" CUSTOMER_BANK_CODE=\"0000018237002012\" CUSTOMER_OPNE_BANK=\"泉州银行股份有限公司漳州龙文支行\" CUSTOMER_ADDRESS=\"福建省漳州市南靖县山城镇人民广场1号\" CUSTOMER_PHONE=\"15060008009\" PRODUCT_NAME=\"保函保费\" AMOUNT=\"660.00\" AMOUNT_OF_CHINAESE=\"陆佰陆拾元整\" OPEN_TIME=\"20250507143111\" SELLER_NAME=\"泉州丰泽得兴融资担保有限公司\" SELLER_CREDIT_CODE=\"339901999999199\" SELLER_BANK_CODE=\"1408875219009008865\" SELLER_OPEN_BANK=\"中国工商银行泉州华城支行\" SELLER_ADDRESS=\"福州市仓山区橘园洲工业园55号楼506单元\" SELLER_PHONE=\"0591-83358772\" HANDLER=\"江\" INVOICE_REMARK=\"电子保函\"></INVOICE_INFO>");


        String text = info.toString().trim().toUpperCase();

        String DZBHMD51 = DigestUtils.md5DigestAsHex(text.getBytes()).toUpperCase();
        String DZBHMD52 = MD5.create().digestHex(text).toUpperCase();

        System.out.println("DZBHMD51 = " + DZBHMD51);
        System.out.println("DZBHMD52 = " + DZBHMD52);


        StringBuilder reSb = new StringBuilder();
        reSb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        reSb.append("<DZBH>")
                .append("<DZBHMD5>" + DZBHMD52 + "</DZBHMD5>")
                .append("<DZBHINFO>" + info.toString() + "</DZBHINFO>")
                .append("</DZBH>");

        return reSb.toString();
    }


    public static Path genOfdStructXml(ElgResourceService elgResourceService, Path targetXmlPath, ApplyOrderInfoDO applyOrderInfoDO, OrganizationDO orgDo, ProjectInfoDO projectInfoDO,
                                       BidCustomerDO bidCustomerDO, GuaranteeDO guaranteeDO, InvoiceInfoDO invoiceInfoDO,
                                       Path guaranteePdf, Path receiveOfd, Path qualificationPath, Path licensePath, Path applyFile, Path applyFileEdc, CenterNoEnum centerNoEnum,String clientId) {
        OfdStructXmlBO xmlBO = OfdStructXmlBO.builder()
                .centerOrderId(applyOrderInfoDO.getCenterOrderId())
                .guaranteeNo(applyOrderInfoDO.getGuaranteeNo())
                .guaranteeInfo(buildGuaranteeInfo(guaranteeDO, bidCustomerDO, centerNoEnum))
                .beneficiaryInfo(buildBeneficiaryInfo(projectInfoDO))
                .bidder(buildBidder(bidCustomerDO))
                .tenderInfo(buildTenderInfo(projectInfoDO, centerNoEnum))
                .guarantor(buildGuarantor(orgDo)).guaranteeAttachment(buildGuaranteeAttachment(elgResourceService, guaranteePdf, receiveOfd, qualificationPath, licensePath, applyFile, applyFileEdc, centerNoEnum))
                .build();

        if (CreateGuaranteeUtil.isIssueInvoice(centerNoEnum,clientId)) {
            xmlBO.setInvoiceInfo(buildInvoiceInfo(invoiceInfoDO));
        }

        String structXmlStr = xmlBO.toString();

        try {
            Files.newOutputStream(targetXmlPath).write(structXmlStr.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException("保存结构化数据失败:" + e.getMessage(), e);
        }
        return targetXmlPath;
    }

    private static OfdStructXmlBO.InvoiceInfo buildInvoiceInfo(InvoiceInfoDO invoiceInfoDO) {
        OfdStructXmlBO.InvoiceInfo invoiceInfo = OfdStructXmlBO.InvoiceInfo.builder().build();
        invoiceInfo.setINVOICE_TITLE(invoiceInfoDO.getInvoiceTitle());
        invoiceInfo.setINVOICE_NO(invoiceInfoDO.getInvoiceNo());
        invoiceInfo.setCUSTOMER_NAME(invoiceInfoDO.getCustomerName());
        invoiceInfo.setCUSTOMER_CREDIT_CODE(invoiceInfoDO.getCustomerCreditCode());
        invoiceInfo.setCUSTOMER_BANK_CODE(invoiceInfoDO.getCustomerBankCode());
        invoiceInfo.setCUSTOMER_OPNE_BANK(invoiceInfoDO.getCustomerOpneBank());
        invoiceInfo.setCUSTOMER_ADDRESS(invoiceInfoDO.getCustomerAddress());
        invoiceInfo.setCUSTOMER_PHONE(invoiceInfoDO.getCustomerPhone());
        invoiceInfo.setPRODUCT_NAME("保函保费");
        invoiceInfo.setAMOUNT(toYuan(invoiceInfoDO.getAmount()));
        invoiceInfo.setAMOUNT_OF_CHINAESE(CurrencyUpperUtil.fenToCurrencyUpper(invoiceInfoDO.getAmount()));
        invoiceInfo.setOPEN_TIME(fmtDate(invoiceInfoDO.getGmtCreate()));
        invoiceInfo.setSELLER_NAME(invoiceInfoDO.getSellerName());
        invoiceInfo.setSELLER_CREDIT_CODE(invoiceInfoDO.getSellerCreditCode());
        invoiceInfo.setSELLER_BANK_CODE(invoiceInfoDO.getSellerBankCode());
        invoiceInfo.setSELLER_OPEN_BANK(invoiceInfoDO.getSellerOpenBank());
        invoiceInfo.setSELLER_ADDRESS(invoiceInfoDO.getSellerAddress());
        invoiceInfo.setSELLER_PHONE(invoiceInfoDO.getSellerPhone());
        invoiceInfo.setHANDLER(invoiceInfoDO.getHandler());
        invoiceInfo.setINVOICE_REMARK(invoiceInfoDO.getInvoiceRemark());
        return invoiceInfo;

    }

    private static OfdStructXmlBO.GuaranteeAttachment buildGuaranteeAttachment(ElgResourceService elgResourceService, Path guaranteePdf, Path receiveOfd, Path qualificationPath, Path licensePath, Path applyFile, Path applyFileEdc, CenterNoEnum centerNoEnum) {
        OfdStructXmlBO.GuaranteeAttachment guaranteeAttachment = OfdStructXmlBO.GuaranteeAttachment.builder().build();
        guaranteeAttachment.setWARRANTY_FILE_NAME("电子保单（合同）原文件." + elgResourceService.getFileType(guaranteePdf));
        guaranteeAttachment.setWARRANTY_MD5(elgResourceService.getFileMD5AsHex(guaranteePdf).toUpperCase());
        guaranteeAttachment.setWARRANTY_PDF_FILE_NAME("电子保单（合同）PDF文件." + elgResourceService.getFileType(guaranteePdf));
        guaranteeAttachment.setWARRANTY_PDF_MD5(elgResourceService.getFileMD5AsHex(guaranteePdf).toUpperCase());
        guaranteeAttachment.setORDER_FILE_NAME("电子保函申请单原文件." + elgResourceService.getFileType(applyFileEdc));
        guaranteeAttachment.setORDER_MD5(elgResourceService.getFileMD5AsHex(applyFileEdc));
        guaranteeAttachment.setORDER_PDF_FILE_NAME("电子保函申请单PDF文件." + elgResourceService.getFileType(applyFile));
        guaranteeAttachment.setORDER_PDF_MD5(elgResourceService.getFileMD5AsHex(applyFile));
        guaranteeAttachment.setQUALFICATION_FILE_NAME("企业资质文件." + elgResourceService.getFileType(qualificationPath));
        guaranteeAttachment.setQUALFICATION_FILE_MD5(elgResourceService.getFileMD5AsHex(qualificationPath));
        guaranteeAttachment.setBUSINESS_LICENSE_FILE_NAME("企业营业执照." + elgResourceService.getFileType(licensePath));
        guaranteeAttachment.setBUSINESS_LICENSE_MD5(elgResourceService.getFileMD5AsHex(licensePath));
        guaranteeAttachment.setOTHER_FILE_NAME("到账证明." + elgResourceService.getFileType(receiveOfd));
        guaranteeAttachment.setOTHER_FILE_MD5(elgResourceService.getFileMD5AsHex(receiveOfd));
        guaranteeAttachment.setCenterNoEnum(centerNoEnum);
        return guaranteeAttachment;

    }

    private static OfdStructXmlBO.BeneficiaryInfo buildBeneficiaryInfo(ProjectInfoDO projectInfoDO) {
        OfdStructXmlBO.BeneficiaryInfo beneficiaryInfo = OfdStructXmlBO.BeneficiaryInfo.builder().build();
        beneficiaryInfo.setBENEFICIARY(projectInfoDO.getTenderer());
        beneficiaryInfo.setBENEFICIARY_CREDIT_CODE(projectInfoDO.getTendererCreditCode());
        beneficiaryInfo.setBENEFICIARY_BANK_ACCOUNT(projectInfoDO.getTendererBankAccount());
        beneficiaryInfo.setBENEFICIARY_BANK_CODE(projectInfoDO.getTendererBankCode());
        beneficiaryInfo.setBENEFICIARY_BANK_OPENBANK(projectInfoDO.getTendererBankOpenbank());
        beneficiaryInfo.setBENEFICIARY_CONTACT(projectInfoDO.getTendererContact());
        beneficiaryInfo.setBENEFICIARY_CONTACT_TEL(projectInfoDO.getTendererContactTel());
        return beneficiaryInfo;

    }

    private static OfdStructXmlBO.GuaranteeInfo buildGuaranteeInfo(GuaranteeDO guaranteeDO, BidCustomerDO bidCustomerDO, CenterNoEnum centerNoEnum) {
        OfdStructXmlBO.GuaranteeInfo guaranteeInfo = OfdStructXmlBO.GuaranteeInfo.builder().build();
        guaranteeInfo.setGUARANTEE_NO(guaranteeDO.getGuaranteeNo());
        guaranteeInfo.setCREATE_TIME(fmtDate(guaranteeDO.getGuaranteeTime()));
        guaranteeInfo.setSERVICE_BEGIN_TIME(fmtDate(guaranteeDO.getServiceBeginTime()));
        guaranteeInfo.setSERVICE_END_TIME(fmtDate(guaranteeDO.getServiceEndTime()));
        guaranteeInfo.setBID_BOND(toYuanNum(guaranteeDO.getBidBond()));
        guaranteeInfo.setAMOUNT(toYuan(guaranteeDO.getAmount()));
        guaranteeInfo.setRATE("0.15");//费率（百分号）如千分五填0.5 按照孙总意思按潮州方式处理，万分制
        guaranteeInfo.setPAY_TYPE("4");//电汇
        guaranteeInfo.setPAY_ACCOUNT(bidCustomerDO.getBankCardNum());
        guaranteeInfo.setPAY_NAME(bidCustomerDO.getBankUserName());
        guaranteeInfo.setPAY_PHONE(bidCustomerDO.getBidderContactTel());
        guaranteeInfo.setPAY_BANK_OPENBANK(bidCustomerDO.getBankName());
        guaranteeInfo.setGUARANTEE_DUTY("连带责任保证");
        guaranteeInfo.setGUARANTEE_PROPERTY("独立保函");
        guaranteeInfo.setCLAIM_CLAUSE("1、投标人在投标有效期内撤销或修改其投标文件的；" +
                "2、投标人中标后，非因不可抗力原因放弃中标、无正当理由不与招标人订立合同、在" +
                "签订合同时向招标人提出附加条件、或者不按照招标文件要求提交履约担保金的；" +
                "3、投标人的投标文件存在投标须知第 20.6 款规定的雷同情形之一；" +
                "4、投标人中标后，因违法行为导致中标被依法确认无效的；" +
                "5、法律、法规规定的其他没收投标保证金情形。" +
                "本保函在投标有效期到期后 28 日（含）内或招标人延长投标有效期后的到期日后 28" +
                "日（含）内保持有效，延长投标有效期无须通知我方，但任何索款要求应在投标有效期内送" +
                "达我方。保函失效后请将本保函交投标人退回我方注销。" +
                "本保函项下所有权利和义务均受中华人民共和国法律管辖和制约。");
        if (CenterNoEnum.NINGDE.equals(centerNoEnum)) {
            guaranteeInfo.setPAY_LIMITATION("10");
        } else {
            guaranteeInfo.setPAY_LIMITATION("7");
        }
        guaranteeInfo.setBANK_RECORD_NO("无");
        guaranteeInfo.setAPPLICABLE_LAW("适用法律：担保法、保险法、《独立保函司法解释》（法释〔2016〕24 号）");
        guaranteeInfo.setREMARK("");
        return guaranteeInfo;

    }

    private static OfdStructXmlBO.Bidder buildBidder(BidCustomerDO bidCustomerDO) {
        OfdStructXmlBO.Bidder bidder = OfdStructXmlBO.Bidder.builder().build();
        bidder.setBIDDER_NAME(bidCustomerDO.getBidderName());
        bidder.setBIDDER_CREDIT_CODE(bidCustomerDO.getBidderCreditCode());
        bidder.setBIDDER_CONTACT_NAME(bidCustomerDO.getBidderContactName());
        bidder.setBIDDER_CONTACT_TEL(bidCustomerDO.getBidderContactTel());
        bidder.setBIDDER_CONTACT_IDCARD(bidCustomerDO.getBidderContactIdcard());
        bidder.setBIDDER_CONTACT_IDCARD_TYPE("01");
        bidder.setBIDDER_ADDRESS(bidCustomerDO.getBidderRegAddress());
        bidder.setBIDDER_EAMIL(bidCustomerDO.getBidderEamil());
        bidder.setLEGAL_PERSON_NAME(bidCustomerDO.getLegalPersonName());
        bidder.setLEGAL_PERSON_IDCARD(bidCustomerDO.getLegalPersonIdcard());
        bidder.setLEGAL_PERSON_IDCARD_TYPE("01");
        bidder.setLEGAL_PERSON_TEL(bidCustomerDO.getLegalPersonTel());

        return bidder;

    }

    private static OfdStructXmlBO.Guarantor buildGuarantor(OrganizationDO orgDo) {
        OfdStructXmlBO.Guarantor guarantor = OfdStructXmlBO.Guarantor.builder().build();
        guarantor.setGUARANTOR_NAME(orgDo.getFullName());
        guarantor.setGUARANTOR_CREDIT_CODE(orgDo.getCreditCode());
        guarantor.setGUARANTOR_LEGAL_PERSON(orgDo.getLegalName());
        guarantor.setGUARANTOR_LEGAL_IDCARD_TYPE("01");
        guarantor.setGUARANTOR_LEGAL_IDCARD(orgDo.getLegalIdcard());
        guarantor.setBANK_CODE("");
        guarantor.setGUARANTOR_ADDRESS(orgDo.getAddress());
        guarantor.setGUARANTOR_EMAIL(orgDo.getContactEmail());
        guarantor.setGUARANTOR_POSTCODE("350001");//必输无值
        guarantor.setGUARANTOR_PHONE(orgDo.getLegalMobile());
        guarantor.setGUARANTOR_TAX("");
        guarantor.setGUARANTOR_BUSSINESS_NAME(orgDo.getContactName());
        guarantor.setGUARANTOR_BUSSINESS_TEL(orgDo.getContactTel());

        String technologyContactName = orgDo.getTechnologyContactName();
        String technologyContactTel = orgDo.getTechnologyContactTel();
        if (StringUtils.isEmpty(technologyContactName)) {
            technologyContactName = orgDo.getContactName();
        }
        if (StringUtils.isEmpty(technologyContactTel)) {
            technologyContactTel = orgDo.getContactTel();
        }

        guarantor.setGUARANTOR_TECHNOLOGY_NAME(technologyContactName);
        guarantor.setGUARANTOR_TECHNOLOGY_TEL(technologyContactTel);

        return guarantor;
    }

    private static OfdStructXmlBO.TenderInfo buildTenderInfo(ProjectInfoDO projectInfoDO, CenterNoEnum centerNoEnum) {
        OfdStructXmlBO.TenderInfo tenderInfo = OfdStructXmlBO.TenderInfo.builder().build();
        tenderInfo.setAPPROVAL_CODE("");
        tenderInfo.setINVEST_PROJECT_CODE("");
        tenderInfo.setTENDER_PROJECT_CODE(projectInfoDO.getProjectCode());
        tenderInfo.setTENDER_PROJECT_NAME(projectInfoDO.getProjectName());
        tenderInfo.setSECTION_CODE(projectInfoDO.getSectionCode());
        tenderInfo.setSECTION_NAME(projectInfoDO.getSectionName());
        tenderInfo.setCONTRACT_RECKON_PRICE(toYuan(projectInfoDO.getContractReckonPrice()));
        tenderInfo.setTENDERER(projectInfoDO.getTenderer());
        tenderInfo.setTENDERER_CREDIT_CODE(projectInfoDO.getTendererCreditCode());
        tenderInfo.setTENDERER_BANK_CODE(projectInfoDO.getTendererBankCode());
        tenderInfo.setTENDERER_BANK_OPENBANK(projectInfoDO.getTendererBankOpenbank());
        tenderInfo.setTENDERER_BANK_ACCOUNT(projectInfoDO.getTendererBankAccount());
        tenderInfo.setTENDERER_CONTACT(projectInfoDO.getTendererContact());
        tenderInfo.setTENDERER_CONTACT_TEL(projectInfoDO.getTendererContactTel());

        tenderInfo.setTENDERER_CONTACT_ADDRESS(projectInfoDO.getTendererAddress());
        tenderInfo.setPROJECT_DAYS(projectInfoDO.getProjectDays());
        tenderInfo.setPROJECT_ADDRESS(projectInfoDO.getProjectAddress());
        tenderInfo.setINVITE_TYPE(projectInfoDO.getInviteType());

        tenderInfo.setCITY_CODE(projectInfoDO.getCityCode());
        tenderInfo.setTENDER_PROJECT_TYPE(projectInfoDO.getTenderProjectType());
        tenderInfo.setBID_OPEN_TIME(fmtDate(projectInfoDO.getBidOpenTime()));
        tenderInfo.setVALID_PERIOD((projectInfoDO.getValidPeriod() == null) ? "0" : projectInfoDO.getValidPeriod().toString());
        tenderInfo.setBID_BOND(toYuanNum(projectInfoDO.getBidBond()));
        tenderInfo.setTENDER_NOTICE_URL(projectInfoDO.getTenderNoticeUrl());
        tenderInfo.setTENDER_FILE_URL(projectInfoDO.getTenderFileUrl());
        tenderInfo.setTENDER_FILE_MD5(projectInfoDO.getTenderFileMd5());
        tenderInfo.setCenterNoEnum(centerNoEnum);

        return tenderInfo;

    }

    private static String fmtDate(Date date) {
        String dateStr = "";
        if (date != null) {
            dateStr = DateFormatUtils.format(date, "yyyyMMddHHmmss");
        }
        return dateStr;
    }

    public static String toYuan(String amt, int scale) {
        if (StringUtils.isBlank(amt)) {
            return "0";
        }
        try {
            BigDecimal bigDecimal = new BigDecimal(amt);
            return bigDecimal.divide(BigDecimal.valueOf(100), scale, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 默认保留小数点0位，按照孙总意思按照潮州方式处理
     *
     * @param amt
     * @return
     */
    private static String toYuan(Long amt) {
        String yuanStr = "0";
        if (amt != null) {
            yuanStr = toYuan(String.valueOf(amt), 2);
        }
        return yuanStr;
    }

    /**
     * 不保留小数，福建省内要求单位为元 NUM(20)
     *
     * @param amt
     * @return
     */
    private static String toYuanNum(Long amt) {
        String yuanStr = "0";
        if (amt != null) {
            yuanStr = toYuan(String.valueOf(amt), 0);
        }
        return yuanStr;
    }

    public static void main(String[] args) throws Exception {


        System.out.println("args = " + OfdStructXmlUtil.toYuan(1234567L));

        String Str = genOfdXmlFile();
        System.out.println("Str = " + Str);

        String rSr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><DZBH><DZBHMD5>C7B58B798C04B4F4CD46BA4E4995DBBC</DZBHMD5><DZBHINFO><ORDER_ID>TBaoHanNDTA2021082708485709216</ORDER_ID><GUARANTEE_NO>6016531184006210049704</GUARANTEE_NO><TENDER_INFO APPROVAL_CODE=\"霞发改【2012】53号\" INVEST_PROJECT_CODE=\"2018-350921-77-01-053575\" TENDER_PROJECT_CODE=\"E3509210902100105001\" TENDER_PROJECT_NAME=\"霞浦县台水中心污水处理厂及配套管网工程(一期）--土建工程\" SECTION_CODE=\"E3509210902100105001001\" SECTION_NAME=\"霞浦县台水中心污水处理厂及配套管网工程(一期）--土建工程\" CONTRACT_RECKON_PRICE=\"25065300.00\" TENDERER=\"霞浦县鑫港建设有限公司\" TENDERER_CREDIT_CODE=\"91350921662833255N\" TENDERER_BANK_CODE=\"13240101040021830\" TENDERER_BANK_OPENBANK=\"中国农业银行霞浦支行\" TENDERER_BANK_ACCOUNT=\"霞浦县鑫港建设有限公司\" TENDERER_CONTACT=\"陈贤东\" TENDERER_CONTACT_TEL=\"17880333700\" CITY_CODE=\"350921\" TENDER_PROJECT_TYPE=\"建设工程\" BID_OPEN_TIME=\"20210906090000\" VALID_PERIOD=\"120\" BID_BOND=\"400000.0\" TENDER_NOTICE_URL=\"http://220.161.207.254/projectDetail.html?categorynum=002001&amp;infoid=bc1dfc2b-500b-419e-9a86-5cb390c6c8fd\" TENDER_FILE_URL=\"http://220.161.207.254:8090/ndzx/JSGCZtbMis2_ND/Pages/DownloadFile/DownloadFile.ashx?AttachGuid=89745a55-d0b9-4136-8523-a923d1221298\" TENDER_FILE_MD5=\"148C92D64BAA469F8E9D207AFA4E5C11\"></TENDER_INFO><GUARANTOR GUARANTOR_NAME=\"天安财产保险股份有限公司宁德中心支公司\" GUARANTOR_CREDIT_CODE=\"91350902791774175H\" GUARANTOR_LEGAL_PERSON=\"黄斌\" GUARANTOR_LEGAL_IDCARD_TYPE=\"01\" GUARANTOR_LEGAL_IDCARD=\"352201197712050016\" BANK_CODE=\"\" GUARANTOR_ADDRESS=\"宁德市东侨经济开发区福宁南路6号中益家居博览中心B座6层604、605、605号\" GUARANTOR_EMAIL=\"mshubin@tianan-insurance.com\" GUARANTOR_POSTCODE=\"352100\" GUARANTOR_PHONE=\"18950501234\" GUARANTOR_TAX=\"\" GUARANTOR_BUSSINESS_NAME=\"马树斌\" GUARANTOR_BUSSINESS_TEL=\"18950501234\" GUARANTOR_TECHNOLOGY_NAME=\"阮泉涛\" GUARANTOR_TECHNOLOGY_TEL=\"18059146048\"></GUARANTOR><BIDDER BIDDER_NAME=\"中彩建设产业发展集团有限公司\" BIDDER_CREDIT_CODE=\"914300006616784334\" BIDDER_CONTACT_NAME=\"李月玲\" BIDDER_CONTACT_TEL=\"15659129848\" BIDDER_CONTACT_IDCARD=\"350721199302134524\" BIDDER_CONTACT_IDCARD_TYPE=\"01\" BIDDER_ADDRESS=\"长沙市芙蓉区八一路10号天佑大厦501房\" BIDDER_EAMIL=\"1157409357@qq.com\" LEGAL_PERSON_NAME=\"尹谷华\" LEGAL_PERSON_IDCARD=\"430181198303063923\" LEGAL_PERSON_IDCARD_TYPE=\"01\" LEGAL_PERSON_TEL=\"18650311911 \"></BIDDER><GUARANTEE_INFO GUARANTEE_NO=\"6016531184006210049704\" CREATE_TIME=\"2021-08-27\" SERVICE_BEGIN_TIME=\"20210906090000\" SERVICE_END_TIME=\"20211205090000\" BID_BOND=\"400000.0\" AMOUNT=\"600.00\" RATE=\"0.2\" PAY_TYPE=\"3\" PAY_ACCOUNT=\"800144293408012\" PAY_NAME=\"中彩建设产业发展集团有限公司\" PAY_PHONE=\"15659129848\" PAY_BANK_OPENBANK=\"长沙银行股份有限公司瑞昌支行\" GUARANTEE_DUTY=\"独立保函\" GUARANTEE_PROPERTY=\"独立保函\" CLAIM_CLAUSE=\"天安保险股份有限公司建设工程施工合同履约保证保险（A版）条款\" PAY_LIMITATION=\"7\" BANK_RECORD_NO=\"保监许可[2016]1120号\" APPLICABLE_LAW=\"保险法\" REMARK=\"\"></GUARANTEE_INFO><BENEFICIARY_INFO BENEFICIARY=\"霞浦县鑫港建设有限公司\" BENEFICIARY_CREDIT_CODE=\"91350921662833255N\" BENEFICIARY_BANK_ACCOUNT=\"霞浦县鑫港建设有限公司\" BENEFICIARY_BANK_CODE=\"13240101040021830\" BENEFICIARY_BANK_OPENBANK=\"中国农业银行霞浦支行\" BENEFICIARY_CONTACT=\"陈贤东\" BENEFICIARY_CONTACT_TEL=\"17880333700\"></BENEFICIARY_INFO><GUARANTEE_ATTACHMENT WARRANTY_FILE_NAME=\"电子保单（合同）原文件.file\" WARRANTY_MD5=\"DD9C358DD22951BA2F212CAD2EE13573\" WARRANTY_PDF_FILE_NAME=\"电子保单（合同）pdf文件.pdf\" WARRANTY_PDF_MD5=\"DD9C358DD22951BA2F212CAD2EE13573\" ORDER_FILE_NAME=\"电子保函申请单文件.file\" ORDER_MD5=\"DD9C358DD22951BA2F212CAD2EE13573\" ORDER_PDF_FILE_NAME=\"电子保函申请单PDF文件.pdf\" ORDER_PDF_MD5=\"DD9C358DD22951BA2F212CAD2EE13573\" QUALFICATION_FILE_NAME=\"企业营业执照文件.jpg\" QUALFICATION_FILE_MD5=\"1FA3BFEC83A45049456716B4157B20A5\" BUSINESS_LICENSE_FILE_NAME=\"企业资质文件.jpg\" BUSINESS_LICENSE_MD5=\"9C490D8F19A030B569B8572D6106E95A\" OTHER_FIE_NAME=\"到账证明.ofd\" OTHER_FIE_MD5=\"79E9D809F5AA363C35415168503DAB63\"></GUARANTEE_ATTACHMENT><INVOICE_INFO INVOICE_TITLE=\"中彩建设产业发展集团有限公司\" INVOICE_NO=\"25151862\" CUSTOMER_NAME=\"中彩建设产业发展集团有限公司\" CUSTOMER_CREDIT_CODE=\"914300006616784334\" CUSTOMER_BANK_CODE=\"800144293408012\" CUSTOMER_OPNE_BANK=\"长沙银行股份有限公司瑞昌支行\" CUSTOMER_ADDRESS=\"长沙市芙蓉区八一路10号天佑大厦501房\" CUSTOMER_PHONE=\"15659129848\" PRODUCT_NAME=\"保函保费\" AMOUNT=\"600.00\" AMOUNT_OF_CHINAESE=\"陆佰元整\" OPEN_TIME=\"2021-08-27\" SELLER_NAME=\"天安财产保险股份有限公司宁德中心支公司\" SELLER_CREDIT_CODE=\"91350902791774175H\" SELLER_BANK_CODE=\"1407002609005003479\" SELLER_OPEN_BANK=\"工商银行宁德蕉城区支行\" SELLER_ADDRESS=\"宁德\" SELLER_PHONE=\"0593-2079989\" HANDLER=\"马树斌\" INVOICE_REMARK=\"\"></INVOICE_INFO></DZBHINFO></DZBH>";
        System.out.println("rSr = " + rSr);

        OfdStructXmlBO bo = OfdStructXmlBO.builder()
                .centerOrderId("TBaoHanNDTA2021082708485709216")
                .guaranteeNo("6016531184006210049704")

                .tenderInfo(OfdStructXmlBO.TenderInfo.builder().APPROVAL_CODE("1111").build())
                .guarantor(OfdStructXmlBO.Guarantor.builder().BANK_CODE("222").build())
                .bidder(OfdStructXmlBO.Bidder.builder().BIDDER_ADDRESS("333").build())
                .guaranteeInfo(OfdStructXmlBO.GuaranteeInfo.builder().AMOUNT("44").build())
                .beneficiaryInfo(OfdStructXmlBO.BeneficiaryInfo.builder().BENEFICIARY("55").build())
                .guaranteeAttachment(OfdStructXmlBO.GuaranteeAttachment.builder().ORDER_PDF_MD5("66").build())
                .invoiceInfo(OfdStructXmlBO.InvoiceInfo.builder().AMOUNT("77").build()).build();


        System.out.println("OfdStructXmlBO = " + bo.toString());

        Path targetXmlPath = Paths.get("d:/kk.xml");
        for (int i = 0; i < 10; i++) {
            Files.newOutputStream(targetXmlPath).write(bo.toString().getBytes(StandardCharsets.UTF_8));
        }

    }

}
